<?php

namespace app\api\service\admin;

use app\common\library\Auth;
use think\Validate;
use think\Db;

class StudentLessonCodesService
{
    // 列表
    public static function index($data)
    {
        try {
            // 参数验证
            if (!isset($data['category_id']) || !is_numeric($data['category_id'])) {
                return ['code' => 400, 'msg' => 'Invalid category_id', 'state' => 'ERROR', 'data' => null];
            }

            if (!isset($data['semester_id']) || !is_numeric($data['semester_id'])) {
                return ['code' => 400, 'msg' => 'Invalid semester_id', 'state' => 'ERROR', 'data' => null];
            }

            // limit 参数处理与限制
            $limit = 10;
            if (isset($data['limit'])) {
                if (!is_numeric($data['limit']) || $data['limit'] < 1 || $data['limit'] > 100) {
                    return ['code' => 400, 'msg' => 'Limit must be between 1 and 100', 'state' => 'ERROR', 'data' => null];
                }
                $limit = (int)$data['limit'];
            }

            // 分页查询
            $studio = \app\admin\model\StudentLessonCodes::where([
                'category_id' => $data['category_id'],
                'semester_id' => $data['semester_id']
            ])->field(['lesson_id', 'code', 'lesson_rang', 'code_type'])
                ->order('lesson_id', 'asc')
                ->paginate($limit);

            return ['code' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $studio];

        } catch (\Exception $e) {
            // 统一异常处理
            return ['code' => 500, 'msg' => 'Server Error: ' . $e->getMessage(), 'state' => 'ERROR', 'data' => null];
        }
    }


    // 保存
    public static function save($data)
    {
        // 验证规则
        $validate = new Validate([
            'category_id' => 'require',
            'semester_id' => 'require',
            'code' => 'require',
            'code_type' => 'require',
            'subject_abbr' => 'require',
            'lesson_rang' => 'require',
        ], [
            'category_id.require' => 'CategoryId is not empty',
            'semester_id.require' => 'SemesterId is not empty',
            'code.require' => 'Code is not empty',
            'code_type.require' => 'Code Type is not empty',
            'subject_abbr.require' => 'Subject Abbr is not empty',
            'lesson_rang.require' => 'Lesson Rang is not empty',
        ]);

        if (!$validate->check($data)) {
            return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务将数据保存到数据库
        try {
            if(isset($data['lesson_id']) && $data['lesson_id']){
                $validate = new Validate([
                    'lesson_id' => 'require',
                ], [
                    'lesson_id.require' => 'LessonId is not empty',
                ]);

                if (!$validate->check($data)) {
                    return ['code'=>400, 'msg'=>$validate->getError(), 'state'=>'INVALID_ARGUMENT', 'data'=>null];
                }
                $result  = \app\admin\model\StudentLessonCodes::update($data);
            }else{
                $result = \app\admin\model\StudentLessonCodes::create($data);
            }
            Db::commit();
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
        return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
    }

    // 删除
    public static function del($data)
    {
        $auth = Auth::instance();
        // 验证$data['id']是否为空且为数字

        if (empty($data['lesson_id']) || !is_numeric($data['lesson_id'])) {
            return ['code'=>400, 'msg'=>'Invalid parameters', 'state'=>'INVALID_ARGUMENT', 'data'=>null];
        }

        // 启用事务删除数据
        try {
            $result = \app\admin\model\StudentLessonCodes::destroy($data['lesson_id']);

            if($result){
                Db::commit();
                return ['code'=>200, 'msg'=>'Successful', 'state'=>'OK', 'data'=>$result];
            }else{
                Db::rollback();
                return ['code'=>400, 'msg'=>'Failed', 'state'=>'FAILED', 'data'=>null];
            }
        }
        catch (\Exception $e) {
            Db::rollback();
            return ['code' => 400, 'msg' => 'Database error: ' . $e->getMessage(), 'state' => 'DATABASE_ERROR', 'data' => null];
        }
    }

    // 下拉查询
    public static function select($data)
    {
        $where = [];

        if (isset($data['category_id']) && $data['category_id']) {
            $where['category_id'] = $data['category_id'];
        }

        if (isset($data['semester_id']) && $data['semester_id']) {
            $where['semester_id'] = $data['semester_id'];
        }

        if (isset($data['subject_id']) && $data['subject_id']) {
            $subject_abbr = \app\admin\model\StudentSubject::where(['subject_id' => $data['subject_id']])->value('abbreviation');
            if ($subject_abbr) {
                $where['subject_abbr'] = $subject_abbr;
            }
        }

        try {
            $lessons = \app\admin\model\StudentLessonCodes::where($where)
                ->field('lesson_id,code,lesson_rang,code_type')
                ->order('lesson_id', 'asc')
                ->select();

            // 获取 level_abbr，避免在循环中重复查询
            $level_abbr = '';
            if (!empty($data['level_id'])) {
                $level_abbr = \app\admin\model\StudentCourseLevel::where(['level_id' => $data['level_id']])
                    ->value('abbreviation');
            }

            if ($lessons) {
                foreach ($lessons as &$lesson) {
                    if ($level_abbr) {
                        $lesson['code'] = $level_abbr . '-' . $lesson['code'];
                    }
                    // 否则保留原样
                }
            }

            return ['status' => 200, 'msg' => 'Successful', 'state' => 'OK', 'data' => $lessons];

        } catch (\Exception $e) {
            // 记录日志（可选）
            return ['status' => 500, 'msg' => 'Internal Server Error', 'state' => 'ERROR', 'data' => []];
        }
    }



}
